import { create } from "zustand";
import apis, { type Me } from "../apis/me";
import type { MeUpdateInput } from "../apis/me/me.types";
import { LOCAL_STORAGE_KEY_TOKEN } from "../misc/dicts";
import type { Stage } from "../types";

type MeStoreState = { me: Stage<Me> };

type MeStoreActions = {
  loadMe: () => Promise<void>;
  updateMe: (input: MeUpdateInput) => Promise<void>;
  afterLogin: (me: Me) => void;
};

export type MeStore = MeStoreState & MeStoreActions;

const useMeStore = create<MeStore>((set, _get) => ({
  me: { type: "loading" },
  loadMe: async () => {
    try {
      set({ me: { type: "loading" } });
      const me = await apis.loadMe();
      set({ me: { type: "ok", data: me } });
    } catch (_e) {
      set({ me: { type: "init" } });
    }
  },
  updateMe: async (input) => {
    const me = await apis.updateMe(input);
    set({ me: { type: "ok", data: me } });
  },
  afterLogin: (me) => {
    set({ me: { type: "ok", data: me } });
    if (me.token) {
      localStorage.setItem(LOCAL_STORAGE_KEY_TOKEN, me.token);
    }
  },
}));

export default useMeStore;
